package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constants.TradeMqConstants;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {
    
    private final IOrderService orderService;
    private final PayClient payClient;

    /**
     * 监听订单延迟消息
     * //1、根据订单id查询订单
     * //2、如果订单不存在或者订单已经支付则无需再处理
     * //3、订单未支付，到支付系统查询最新订单支付状态
     * //3.1、如果已经支付则更新订单状态
     * //3.2、如果还未支付，说明已经超时，则取消订单
     * @param orderId 订单id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = TradeMqConstants.DELAY_ORDER_QUEUE, durable = "true"),
            exchange = @Exchange(value = TradeMqConstants.DELAY_EXCHANGE, type = ExchangeTypes.TOPIC,
                   delayed = "true"),
            key = TradeMqConstants.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenOrderDelayMsg(Long orderId){
        //1、获取延迟消息中的订单id；到支付微服务pay-service中根据订单id查询支付订单
        PayOrderDTO payOrderDTO = payClient.queryPayOrderDTOByOrderId(orderId);
        if(payOrderDTO == null){
            return;
        }

        //2、如果订单已经支付，则更新订单状态为已支付；
        if(payOrderDTO.getStatus() == 3){
            orderService.markOrderPaySuccess(orderId);
            return;
        }
        //3、如果订单没有支付，取消订单
        orderService.cancelOrder(orderId);
    }
}